

# Ülkeye göre korelasyon tabloları
library(dplyr)
library(ggplot2)
library(patchwork) 
source("PROCESS_R/process.R")
library(lavaan)
library(psych)
library(rempsyc)
library(effectsize)
library(flextable)
library(broom)
library(report)



###### CFA ##### SF-12



sf12_model <- '
  # Physical Component Summary (PCS)
  PCS =~ q1_2_rev + q2_2 + q3_2 + q4_2 + q5_2 + q8_2_rev

  # Mental Component Summary (MCS)
  MCS =~ q6_2 + q7_2 + q9_2_rev + q10_2_rev + q11_2 + q12_2

  # Faktörler arası korelasyon (serbest bırakılır)
  PCS ~~ MCS
'

fit_sf12_mg <- cfa(
  sf12_model,
  data    = yasli,
  group   = "country",
  estimator = "MLR",
  missing   = "fiml"
)
summary(fit_sf12_mg, fit.measures = TRUE, standardized = TRUE)





#### Loneliness


loneliness_model_2f <- '
  # Sosyal yalnızlık faktörü
  Social =~ l1_2 + l4_2 + l7_2 + l8_2 + l11_2

  # Duygusal yalnızlık faktörü
  Emotional =~ l2_2t + l3_2t + l5_2t + l6_2t + l9_2t + l10_2t

  # Faktörler arası korelasyon
  Social ~~ Emotional
'

fit_loneliness_mg <- cfa(
  loneliness_model_2f,
  data    = yasli,
  group   = "country",
  estimator = "MLR",
  missing   = "fiml"
)
summary(fit_loneliness_mg, fit.measures = TRUE, standardized = TRUE)




##### Demographic Variables
colnames(yasli)


demo <- yasli %>%
  dplyr::select(
    country,
    sex_t1,
    age_t2,
    marital_status_t3,
    born_t4,
    education_t5,
    income_z
  )

demo %>%
  group_by(country) %>%
  summarise(
    n = n(),
    mean_age = mean(age_t2, na.rm = TRUE),
    sd_age = sd(age_t2, na.rm = TRUE),
    mean_income_z = mean(income_z, na.rm = TRUE),
    sd_income_z = sd(income_z, na.rm = TRUE)
  )

demo %>%
  group_by(country, sex_t1) %>%
  summarise(n = n()) %>%
  mutate(percent = round(n / sum(n) * 100, 1))

demo %>%
  group_by(country, marital_status_t3) %>%
  summarise(n = n()) %>%
  mutate(percent = round(n / sum(n) * 100, 1))

demo %>%
  group_by(country, education_t5) %>%
  summarise(n = n()) %>%
  mutate(percent = round(n / sum(n) * 100, 1))

demo %>%
  group_by(country, born_t4) %>%
  summarise(n = n()) %>%
  mutate(percent = round(n / sum(n) * 100, 1))



#-------------------
# Correlation
#-----------------
unique(yasli$country)
# Ülke değişkeninin adı country ise:
turkiye <- yasli %>% filter(country == "Türkiye")
almanya <- yasli %>% filter(country == "Almanya")

vars <- c("total_lonliness", "Total_Fraility", "Total_QoL", "PCS12", "MCS12")

cor_turkiye <- cor(turkiye[vars], use = "pairwise.complete.obs", method = "pearson")
cor_almanya <- cor(almanya[vars], use = "pairwise.complete.obs", method = "pearson")

cor_turkiye
cor_almanya

cor_p_turkiye <- psych::corr.test(turkiye[vars], adjust = "none")
cor_p_almanya <- psych::corr.test(almanya[vars], adjust = "none")

cor_p_turkiye
cor_p_almanya





mean_sd_turkiye <- turkiye[vars] %>% summarise_all(~paste0(round(mean(.),2), " (", round(sd(.),2), ")"))
mean_sd_almanya <- almanya[vars] %>% summarise_all(~paste0(round(mean(.),2), " (", round(sd(.),2), ")"))

mean_sd_turkiye
mean_sd_almanya


#------------------------
# T-Test
#-------------------------
results <- nice_t_test(
  data = yasli,
  response = vars,
  group = "country",
  adjustment = "bonferroni"   # Otomatik düzeltme
)

results
#-----------------
#SEM 
#------------------


process(y = "Total_QoL",
        x = "total_lonliness",
        m = "Total_Fraility",
        w = "country_n",
        cov = c("sex_n", "age_t2", "marital_n", "income_n"),   # ← COVARIATES
        model = 58,
        jn = 1,
        plot = 1,
        decimals = 10.5,
        seed = 42517,
        boot = 5000,
        progress = 0,
        data = yasli)





process(
  y = "Total_QoL",
  x = "total_lonliness",
  m = "Total_Fraility",
  cov = c("sex_n", "age_t2", "marital_n", "income_n"),
  model = 4,
  boot = 5000,
  seed = 42517,
  data = turkiye
)


process(
  y = "Total_QoL",
  x = "total_lonliness",
  m = "Total_Fraility",
  cov = c("sex_n", "age_t2", "marital_n", "income_n"),
  model = 4,
  boot = 5000,
  seed = 42517,
  data = almanya
)



#### Interaction Graphics ########


# -------------------
# Panel A: Loneliness → Frailty
# -------------------
df1 <- data.frame(
  Loneliness = rep(c(2, 9, 14.4), 2),
  Country = factor(rep(c("Türkiye (W=0)", "Germany (W=1)"), each = 3),
                   levels = c("Türkiye (W=0)", "Germany (W=1)")),
  Frailty = c(5.06, 6.53, 7.66, 4.68, 6.15, 7.28)
)

p1 <- ggplot(df1, aes(x = Loneliness, y = Frailty,
                      color = Country, shape = Country, linetype = Country)) +
  geom_line(linewidth = 1.2) +
  geom_point(size = 3) +
  scale_color_manual(values = c("grey40", "black")) +
  scale_linetype_manual(values = c("dashed", "solid")) +
  scale_shape_manual(values = c(15, 17)) +
  labs(title = "Conditional Effect of Loneliness on Frailty by Country",
       x = "Loneliness (X)",
       y = "Frailty (M)") +
  theme_bw(base_size = 15, base_family = "serif") +
  theme(
    plot.title = element_text(face = "bold", size = 13, hjust = 0.5),
    legend.position = c(0.86, 0.105),  # GRAFİK İÇİNE TAŞINDI (x, y)
    legend.background = element_rect(fill = "white", color = "grey70"),
    legend.title = element_blank(),
    legend.key = element_blank(),
    legend.text = element_text(size = 11),
  )


# -------------------
# Panel B: Frailty → QoL
# -------------------
df2 <- data.frame(
  Frailty = rep(c(3, 6, 9), 2),
  Country = factor(rep(c("Türkiye (W=0)", "Germany (W=1)"), each = 3),
                   levels = c("Türkiye (W=0)", "Germany (W=1)")),
  QoL = c(90.47, 85.98, 81.48, 88.54, 80.62, 72.70)
)

p2 <- ggplot(df2, aes(x = Frailty, y = QoL,
                      color = Country, shape = Country, linetype = Country)) +
  geom_line(linewidth = 1.2) +
  geom_point(size = 3) +
  scale_color_manual(values = c("grey40", "black")) +
  scale_linetype_manual(values = c("dashed", "solid")) +
  scale_shape_manual(values = c(15, 17)) +
  labs(title = "Conditional Effect of Frailty on QoL by Country",
       x = "Frailty (M)",
       y = "QoL-SF12 (Y)") +
  theme_bw(base_size = 15, base_family = "serif") +
  theme(
    plot.title = element_text(face = "bold", size = 13, hjust = 0.5),
    legend.position = c(0.14, 0.105),
    legend.background = element_rect(fill = "white", color = "grey70"),
    legend.title = element_blank(),
    legend.key = element_blank(),
    legend.text = element_text(size = 11)
  )


# -------------------
# İki paneli dikey birleştir
# -------------------
final_plot <- p1 / p2 +
  plot_annotation(theme = theme(plot.margin = margin(5, 5, 5, 5)))

# -------------------
# Çiz ve kaydet


ggsave("Figure_Mediation_Panels_insideLegend.png",
       final_plot, width = 7, height = 10, dpi = 300)



























# -------------------
# Sub dimentions of  QoL with Frailty - PCS
# -------------------
df1 <- data.frame(
  Loneliness = rep(c(2, 9, 14.4), 2),
  Country = factor(rep(c("Türkiye (W=0)", "Germany (W=1)"), each = 3),
                   levels = c("Türkiye (W=0)", "Germany (W=1)")),
  Frailty = c(5.06, 6.53, 7.65, 4.67, 6.14, 7.28)
)

p1 <- ggplot(df1, aes(x = Loneliness, y = Frailty,
                      color = Country, shape = Country, linetype = Country)) +
  geom_line(linewidth = 1.2) +
  geom_point(size = 3) +
  scale_color_manual(values = c("grey40", "black")) +
  scale_linetype_manual(values = c("dashed", "solid")) +
  scale_shape_manual(values = c(15, 17)) +
  labs(title = "Conditional Effect of Frailty on PCS",
       x = "Loneliness (X)",
       y = "Frailty (M)") +
  theme_bw(base_size = 15, base_family = "serif") +
  theme(
    plot.title = element_text(face = "bold", size = 13, hjust = 0.5),
    legend.position = c(0.86, 0.105),  # GRAFİK İÇİNE TAŞINDI (x, y)
    legend.background = element_rect(fill = "white", color = "grey70"),
    legend.title = element_blank(),
    legend.key = element_blank(),
    legend.text = element_text(size = 11),
  )


# -------------------
# Sub dimentions of  QoL with Frailty - MCS
# -------------------
df2 <- data.frame(
  Frailty = rep(c(3, 6, 9), 2),
  Country = factor(rep(c("Türkiye (W=0)", "Germany (W=1)"), each = 3),
                   levels = c("Türkiye (W=0)", "Germany (W=1)")),
  QoL = c(90.47, 85.98, 81.48, 88.54, 80.62, 72.70)
)

p2 <- ggplot(df2, aes(x = Frailty, y = QoL,
                      color = Country, shape = Country, linetype = Country)) +
  geom_line(linewidth = 1.2) +
  geom_point(size = 3) +
  scale_color_manual(values = c("grey40", "black")) +
  scale_linetype_manual(values = c("dashed", "solid")) +
  scale_shape_manual(values = c(15, 17)) +
  labs(title = "Conditional Effect of Frailty on MCS",
       x = "Frailty (M)",
       y = "QoL-SF12 (Y)") +
  theme_bw(base_size = 15, base_family = "serif") +
  theme(
    plot.title = element_text(face = "bold", size = 13, hjust = 0.5),
    legend.position = c(0.14, 0.105),
    legend.background = element_rect(fill = "white", color = "grey70"),
    legend.title = element_blank(),
    legend.key = element_blank(),
    legend.text = element_text(size = 11)
  )


# -------------------
# İki paneli dikey birleştir
# -------------------
final_plot <- p1 / p2 +
  plot_annotation(theme = theme(plot.margin = margin(5, 5, 5, 5)))

# -------------------
# Çiz ve kaydet


ggsave("PCS_MCS",
       final_plot, width = 7, height = 10, dpi = 300)



